import jwt, { JwtPayload } from 'jsonwebtoken';
import { NextFunction, Request, Response } from 'express';
import { config as dotEnvConfig } from 'dotenv';
import { IUserInfo } from '../controllers/User';

dotEnvConfig();

export async function checkAuth(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const auth = req.headers.authorization;
  //检查是否带有`authorization`请求头的API请求
  if (!auth) {
    return res.status(200).json({
      err_code: 1005,
      err_msg: 'The API must tabe the Authorization.'
    });
  }
  //获取Authorization字段的内容，只取出arr[1]部分作为解密前的token值
  //Bearer eyJhbGciOiJIUzI1NiIsInR5cCI......
  const rawToken = auth.split(' ')[1];
  //解密过程
  try {
    //jwt.verify(原始token,服务器私钥)
    const tokenData = jwt.verify(
      rawToken,
      process.env.SECRET_KEY!
    ) as JwtPayload;
    if (!tokenData) {
      return res.status(200).json({
        err_code: 1006,
        err_msg: 'Invalid token'
      });
    }
    //将解密后的id追加给req对象
    req.id = tokenData.id;
    next();
  } catch (e) {
    res.status(200).json({
      err_code: 1007,
      err_msg: 'Token verify failed.'
    });
  }
}

export function checkBody(req: Request, res: Response, next: NextFunction) {
  const { username, password }: IUserInfo = req.body;
  if (username.length < 6 || password.length < 6) {
    return res.status(200).json({
      err_code: 1001,
      err_msg: 'Invalid username or password length.'
    });
  } else {
    next();
  }
}
